using Microsoft.AspNetCore.Http;
using Leo.Core.Identity.Contracts;
using Leo.Core.Jwt;
using System.Linq;
namespace Leo.Core.Identity
{
    public class JwtTokenProvider : ITokenProvider
    {
        protected readonly IHttpContextAccessor HttpContextAccessor;

        public JwtTokenProvider(IHttpContextAccessor httpContextAccessor)
        {
            HttpContextAccessor = httpContextAccessor;
        }

        protected virtual string GetTokenFromHttpHeader()
        {
            if (HttpContextAccessor.HttpContext?.Request?.Headers == null)
                return null;

            return HttpContextAccessor.HttpContext.Request.Headers.TryGetValue(JwtConsts.AuthorizationHeader, out var jwt) ? jwt.FirstOrDefault().Replace(JwtConsts.JwtHeaderPrefix, string.Empty) : null;
        }

        protected virtual string GetTokenFromCookie()
        {
            if (HttpContextAccessor.HttpContext?.Request?.Cookies == null)
                return null;

            return HttpContextAccessor.HttpContext.Request.Cookies.TryGetValue(JwtConsts.CookieName, out var token) ? token : null;
        }


        public virtual string Token => GetTokenFromHttpHeader() ?? GetTokenFromCookie();
    }
}
